import os
import subprocess
import tempfile
from typing import Dict, Optional, Any, Tuple

class DeepSpeechProvider:
    """DeepSpeech provider for speech recognition."""

    def __init__(
        self,
        model_path: str,
        scorer_path: Optional[str] = None,
        **kwargs: Any,
    ):
        """Initialize the DeepSpeech provider.

        Args:
            model_path: Path to the DeepSpeech model file (.pbmm)
            scorer_path: Path to the DeepSpeech scorer file (.scorer)
            **kwargs: Additional arguments to pass to the DeepSpeech command
        """
        self.model_path = model_path
        self.scorer_path = scorer_path
        self.kwargs = kwargs

    def speech_to_text(self, audio_bytes: bytes, sample_rate: int, **kwargs: Any) -> str:
        """Convert speech to text using DeepSpeech.

        Args:
            audio_bytes: Audio bytes to convert to text
            sample_rate: Sample rate of the audio
            **kwargs: Additional arguments to pass to the DeepSpeech command

        Returns:
            Transcribed text
        """
        merged_kwargs = {**self.kwargs, **kwargs}

        # Create a temporary WAV file for DeepSpeech to process
        with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_file:
            temp_file_path = temp_file.name
            temp_file.write(audio_bytes)

        try:
            cmd = ["deepspeech", "--model", self.model_path]
            
            if self.scorer_path:
                cmd.extend(["--scorer", self.scorer_path])
            
            cmd.extend(["--audio", temp_file_path])
            
            # Add any additional arguments
            for key, value in merged_kwargs.items():
                if isinstance(value, bool) and value:
                    cmd.append(f"--{key}")
                else:
                    cmd.extend([f"--{key}", str(value)])
            
            # Run the DeepSpeech command
            result = subprocess.run(
                cmd,
                capture_output=True,
                text=True,
                check=True,
            )
            
            # DeepSpeech outputs the transcription to stdout
            return result.stdout.strip()
        finally:
            # Clean up the temporary file
            if os.path.exists(temp_file_path):
                os.remove(temp_file_path)

    @classmethod
    def get_available_voices(cls) -> Dict[str, Dict[str, Any]]:
        """Get available voices for the DeepSpeech provider.

        Returns:
            Dictionary of available voices (empty for DeepSpeech)
        """
        # DeepSpeech doesn't have the concept of voices
        return {}
